/*
 * http://code.google.com/p/anttesttools/
 * jar: commons-net-*.jar commons-net-ftp-*.jar
 */
package anttesttools.apachecommons;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author anttesttools
 */
public class Ftp
{

    private static Logger log = LoggerFactory.getLogger(Ftp.class);
    private FTPClient ftp = null;
    private String host = null;
    private int port = 21;
    private String user = null;
    private String passwd = null;
    private int reply = 0;

    public Ftp()
    {
        ftp = new FTPClient();
    }

    public void connect()
    {
        try
        {
            ftp.connect(getHost(), port);
            ftp.login(getUser(), passwd);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply))
            {
                log.error("Ftp to IP:{} error", getHost());
                ftp.disconnect();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void setPath(String path)
    {
        try
        {
            log.debug("working path = {}", path);
            ftp.changeWorkingDirectory(path);
            log.debug("change to path = {}", ftp.printWorkingDirectory());
        }
        catch (Exception e)
        {
            log.error(e.getMessage());
        }

    }

    public void down(File localFile, String remoteFile)
    {
        try
        {
            OutputStream is = new FileOutputStream(localFile);
            ftp.retrieveFile(remoteFile, is);
            is.close();
            log.info("OK");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void logout()
    {
        try
        {
            ftp.logout();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * @param host the host to set
     */
    public void setHost(String host)
    {
        this.host = host;
    }

    /**
     * @param port the port to set
     */
    public void setPort(int port)
    {
        this.port = port;
    }

    /**
     * @param user the user to set
     */
    public void setUser(String user)
    {
        this.user = user;
    }

    /**
     * @param passwd the passwd to set
     */
    public void setPasswd(String passwd)
    {
        this.passwd = passwd;
    }

    /**
     * @return the host
     */
    public String getHost()
    {
        return host;
    }

    /**
     * @return the user
     */
    public String getUser()
    {
        return user;
    }
}
